package cn.lby.tp.myapplication;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.zxing.activity.CaptureActivity;
import com.hpplay.sdk.source.api.LelinkSourceSDK;
import com.hpplay.sdk.source.browse.api.IServiceInfoParseListener;
import com.hpplay.sdk.source.browse.api.LelinkServiceInfo;

import java.util.List;

import cn.lby.tp.myapplication.adapter.BrowseAdapter;
import cn.lby.tp.myapplication.constants.Constant;
import cn.lby.tp.myapplication.fragment.DramaFragment;
import cn.lby.tp.myapplication.fragment.MirrorFragment;
import cn.lby.tp.myapplication.fragment.PushFragment;
import cn.lby.tp.myapplication.manager.CastManager;
import cn.lby.tp.myapplication.manager.DeviceManager;
import cn.lby.tp.myapplication.utils.CameraPermissionCompat;
import cn.lby.tp.myapplication.utils.Utils;

/**
 * jasinCao
 * 19-7-25 下午2:50
 */
public class APICastActivity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = "MainActivity";
    private static final int REQUEST_MUST_PERMISSION = 100;
    private static final int REQUEST_CAMERA_PERMISSION = 2;

    private TextView mSDKVersion, mPhoneWifi, mPhoneIP;
    private RecyclerView mBrowseRecyclerView;
    private BrowseAdapter mBrowseAdapter;
    private NetworkReceiver mNetworkReceiver;
    private PushFragment mPushFragment;
    private DramaFragment mDramaFragment;
    private MirrorFragment mMirrorFragment;
    private Button mPushBtn, mMirrorBtn;
    private Button mConnectBtn, mDisconnectBtn;
    private CheckBox mDlnaCheckBox;
//    private RelativeLayout mFrameLayout = null;

    private final IUIUpdateListener mUIListener = new IUIUpdateListener() {
        @Override
        public void onUpdateDevices(List<LelinkServiceInfo> list) {
            updateBrowseAdapter(list);
        }

        @Override
        public void onConnect(LelinkServiceInfo info) {
        }

        @Override
        public void onDisconnect(LelinkServiceInfo info) {
        }

        @Override
        public void onNetChanged() {
            refreshWifiName();
        }

        @Override
        public void onBindSuccess() {
        }
    };

    private final BrowseAdapter.OnSelectListener mOnSelectListener = hasSelected -> {
        mPushBtn.setEnabled(hasSelected);
        mMirrorBtn.setEnabled(hasSelected);
        mConnectBtn.setEnabled(hasSelected);
        mDisconnectBtn.setEnabled(hasSelected);
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_api_cast);
//        mFrameLayout = findViewById(R.id.contain_id);

        if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED
                || ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_DENIED
                || ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_DENIED) {
            ActivityCompat.requestPermissions(this, new String[]{
                            Manifest.permission.WRITE_EXTERNAL_STORAGE
                            , Manifest.permission.ACCESS_FINE_LOCATION
                            , Manifest.permission.ACCESS_COARSE_LOCATION}
                    , REQUEST_MUST_PERMISSION);
            return;
        }
        initSDK();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (grantResults.length < 1 || grantResults[0] != PackageManager.PERMISSION_GRANTED) {
            Logger.w(TAG, "onRequestPermissionsResult ignore ");
            finish();
            return;
        }
        if (requestCode == CameraPermissionCompat.REQUEST_CODE_CAMERA) {
            Logger.w(TAG, "onRequestPermissionsResult ignore camera");
            return;
        }
        initSDK();
        if (CameraPermissionCompat.REQUEST_CODE_CAMERA == requestCode) {
            startCaptureActivity();
        }
    }

    private void initSDK() {
        DeviceManager connectManager = DeviceManager.getInstance();

        connectManager.addUIListener(mUIListener);
        //sdk初始化
        LelinkSourceSDK.getInstance()
                .setBindSdkListener(connectManager.getBindListener())
                .setBrowseResultListener(connectManager.getBrowseListener())
                .setConnectListener(connectManager.getConnectListener())
                .setNewPlayListener(CastManager.getInstance().getPlayerListener())
                //FIXME WARN: 这里替换为您申请的AppID & AppSecret，build.gradle替换为您的应用包名
                .setSdkInitInfo(getApplicationContext(), getString(R.string.app_id), getString(R.string.app_secret))
                .bindSdk();
        initView();
        mNetworkReceiver = new NetworkReceiver();
        mNetworkReceiver.setUIListener(mUIListener);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Constant.WIFI_AP_STATE_CHANGED_ACTION);
        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(mNetworkReceiver, intentFilter);
    }

    private void initView() {
        mDlnaCheckBox = findViewById(R.id.browse_dlna);
        mPhoneWifi = findViewById(R.id.tv_wifi);
        mPhoneIP = findViewById(R.id.tv_ip);
        refreshWifiName();
        mPushBtn = findViewById(R.id.btn_push);
        mPushBtn.setEnabled(false);
        mMirrorBtn = findViewById(R.id.btn_mirror);
        mMirrorBtn.setEnabled(false);
        mConnectBtn = findViewById(R.id.btn_connect);
        mConnectBtn.setEnabled(false);
        mDisconnectBtn = findViewById(R.id.btn_disconnect);
        mDisconnectBtn.setEnabled(false);
        mBrowseRecyclerView = findViewById(R.id.recycler_browse);
        mBrowseAdapter = new BrowseAdapter(getApplicationContext());
        mBrowseAdapter.setOnSelectListener(mOnSelectListener);

        mBrowseRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mBrowseRecyclerView.setAdapter(mBrowseAdapter);
        mBrowseAdapter.setOnItemClickListener((position, info) -> {
            mBrowseAdapter.setSelectServiceInfo(info);
        });
        mSDKVersion = findViewById(R.id.tv_version);
        mSDKVersion.setText("SDK:"
                + com.hpplay.sdk.source.api.BuildConfig.BUILD_TYPE
                + "-" + com.hpplay.sdk.source.api.BuildConfig.VERSION_NAME
                + "    " + com.hpplay.sdk.source.api.BuildConfig.BUILD_TIME);
    }

    public void showScreenCodeDialog() {
        final EditText editText = new EditText(this);
        new AlertDialog.Builder(this).setTitle("请输入投屏码")
                .setView(editText)
                .setPositiveButton("确定", (diaLoggerInterface, i) -> {
                    if (TextUtils.isEmpty(editText.getText().toString())) {
                        DemoApplication.toast("请输入屏幕码");
                        return;
                    }
                    getPinCodeDevice(editText.getText().toString());
                }).setNegativeButton("取消", null).show();
    }

    public void getPinCodeDevice(String castCode) {
        LelinkSourceSDK.getInstance().addPinCodeToLelinkServiceInfo(castCode, new IServiceInfoParseListener() {
            @Override
            public void onParseResult(int resultCode, LelinkServiceInfo lelinkServiceInfo) {
                if (resultCode == IServiceInfoParseListener.PARSE_SUCCESS) {
                    DemoApplication.toast("pin码解析成功");
                } else {
                    DemoApplication.toast("pin码解析失败");
                }
            }
        });
    }

    public void getQRCodeDevice(String qrUrl) {
        Logger.i(TAG, "getQRCodeDevice: " + qrUrl);
        LelinkSourceSDK.getInstance().addQRCodeToLelinkServiceInfo(qrUrl, new IServiceInfoParseListener() {
            @Override
            public void onParseResult(int resultCode, LelinkServiceInfo lelinkServiceInfo) {
                if (resultCode == IServiceInfoParseListener.PARSE_SUCCESS) {
                    DemoApplication.toast("扫码成功");
                } else {
                    DemoApplication.toast("扫码失败");
                }
            }
        });
    }

    private void startCaptureActivity() {
        CameraPermissionCompat.checkCameraPermission(this, granted -> {
            Logger.i(TAG, "checkCameraPermission:" + granted);
            if (granted) {
                // 允许，打开二维码
                Intent intent = new Intent(APICastActivity.this, CaptureActivity.class);
                startActivityForResult(intent, REQUEST_CAMERA_PERMISSION);
            } else {
                // 若没有授权，会弹出一个对话框（这个对话框是系统的，开发者不能自己定制），用户选择是否授权应用使用系统权限
            }
        });
    }

    @Override
    public void onClick(View v) {
        LelinkServiceInfo selectInfo = mBrowseAdapter.getSelectServiceInfo();
        switch (v.getId()) {
            case R.id.btn_browse:
                LelinkSourceSDK.getInstance().startBrowse(
                        true, mDlnaCheckBox.isChecked());
                break;
            case R.id.btn_stop_browse:
                LelinkSourceSDK.getInstance().stopBrowse();
                break;
            case R.id.btn_qrcode:
                startCaptureActivity();
                break;
            case R.id.btn_pincode_connect:
                showScreenCodeDialog();
                break;
            case R.id.btn_push:
                if (selectInfo == null) {
                    DemoApplication.toast("请先选择接收端设备");
                    return;
                }
                if (mPushFragment == null) {
                    mPushFragment = new PushFragment();
                }
                DeviceManager.getInstance().setSelectInfo(selectInfo);
                if (mPushFragment.isAdded()) {
                    return;
                }
                try {
                    getSupportFragmentManager()
                            .beginTransaction()
                            .add(R.id.container, mPushFragment)
                            .addToBackStack("push")
                            .commitAllowingStateLoss();
                } catch (Exception e) {
                    Logger.w(TAG, e);
                }
                break;
            case R.id.btn_drama:
                if (mDramaFragment == null) {
                    mDramaFragment = new DramaFragment();
                }
                if (mDramaFragment.isAdded()) {
                    return;
                }
                mDramaFragment.setSelectInfo(selectInfo);
                try {
                    getSupportFragmentManager()
                            .beginTransaction()
                            .add(R.id.container, mDramaFragment)
                            .addToBackStack("drama")
                            .commitAllowingStateLoss();
                } catch (Exception e) {
                    Logger.w(TAG, e);
                }
                break;
            case R.id.btn_mirror:
//                if (selectInfo == null) {
//                    DemoApplication.toast("请先选择接收端设备");
//                    return;
//                }
                if (mMirrorFragment == null) {
                    mMirrorFragment = new MirrorFragment();
                }
                DeviceManager.getInstance().setSelectInfo(selectInfo);
                if (mMirrorFragment.isAdded()) {
                    return;
                }
                try {
                    getSupportFragmentManager()
                            .beginTransaction()
                            .add(R.id.container, mMirrorFragment)
                            .addToBackStack("mirror")
                            .commitAllowingStateLoss();
                } catch (Exception e) {
                    Logger.w(TAG, e);
                }
                break;
            case R.id.btn_connect:
                if (selectInfo == null) {
                    DemoApplication.toast("请先选择接收端设备");
                    return;
                }
                LelinkSourceSDK.getInstance().connect(selectInfo);
                break;
            case R.id.btn_disconnect:
                if (selectInfo == null) {
                    DemoApplication.toast("请先选择接收端设备");
                    return;
                }
                LelinkSourceSDK.getInstance().disconnect(selectInfo);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != Activity.RESULT_OK) {
            return;
        }
        if (REQUEST_CAMERA_PERMISSION == requestCode) {
            String scanResult = data.getStringExtra(CaptureActivity.INTENT_EXTRA_KEY_QR_SCAN);
            Logger.i(TAG, "onActivityResult url:" + scanResult);
            getQRCodeDevice(scanResult);
        }
    }

    private void updateBrowseAdapter(final List<LelinkServiceInfo> infos) {
        DemoApplication.runOnUI(() -> mBrowseAdapter.updateDatas(infos));
    }

    public void refreshWifiName() {
        mPhoneWifi.setText("WiFi:" + Utils.getNetWorkName(getApplicationContext()));
        mPhoneIP.setText(Utils.getIP(getApplicationContext()));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LelinkSourceSDK.getInstance().stopBrowse();
//        LelinkSourceSDK.getInstance().stopPlay();
//        LelinkSourceSDK.getInstance().unBindSdk();
        if (mNetworkReceiver != null) {
            unregisterReceiver(mNetworkReceiver);
            mNetworkReceiver = null;
        }
    }

}
